package com.dfbz.dao.base;

import com.dfbz.annotation.MyField;
import com.dfbz.annotation.MyTable;
import com.dfbz.model.UserInfo;
import com.dfbz.utils.JDBCUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class BaseDao <T>{
    private final Class<T> aClass;
    private final String tableName;
    private final String keyName;
    public BaseDao(Class<T> aClass){
        this.aClass=aClass;
        MyTable annotation = aClass.getDeclaredAnnotation(MyTable.class);
        if (null!=annotation){
            tableName = annotation.value();
            keyName = annotation.key();
        }else {
            tableName="tbn";
            keyName="id";
        }
    }

    public List<T> findByCol(String key, String value){

        String sql="select * from "+tableName+" where "+key+"=?";
        QueryRunner qr = new QueryRunner(JDBCUtil.getDataSource());
        List<T> userList=new ArrayList<>();
        try {
            userList = qr.query(sql, new BeanListHandler<>(aClass),value);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userList;
    }

    public List<T> findByCols(String condition, Map<String,Object> map){
        StringBuilder builder = new StringBuilder();
        builder.append("select * from ").append(tableName).append(" where ");
        //判断里面有没有内容
        if (null==map||map.isEmpty()){
            builder.delete(builder.lastIndexOf("where"),builder.length());
        }else {
            //遍历map集合，动态拼接条件
            Set<String> keySet = map.keySet();
            for (String key :keySet) {
                builder.append(key).append("='").append(map.get(key)).append("' ").append(condition).append(" ");
            }
            builder.delete(builder.lastIndexOf(condition),builder.length());
        }
        QueryRunner qr = new QueryRunner(JDBCUtil.getDataSource());
        List<T> userList=new ArrayList<>();
        try {
            userList = qr.query(builder.toString(), new BeanListHandler<>(aClass));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userList;
    }

    public int save(Object obj){
        int row=0;
        StringBuilder sb=new StringBuilder();
        sb.append("insert into ").append(tableName).append(" values(");

        Class<?> aClass = obj.getClass();
        Field[] fields = aClass.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            if (i==fields.length-1){
                //遍历到最后一个
                sb.append("?)");
            }else {
                sb.append("?,");
            }
        }

        QueryRunner qr = new QueryRunner(JDBCUtil.getDataSource());
        try {
            Object[] params=new Object[fields.length];
            for (int i = 0; i < fields.length; i++) {
                String fieldName = fields[i].getName();
                String methodName ="get"+ fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                Method method = aClass.getDeclaredMethod(methodName);
                Object value = method.invoke(obj);
                params[i]=value;
            }

            row = qr.update(sb.toString(), params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return row;
    }

    public int update(Object obj){
        int row=0;
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(tableName).append(" set ");

        Class<?> aClass = obj.getClass();
        Field[] fields = aClass.getDeclaredFields();
        for (Field field : fields) {
            String colName = field.getName();
            MyField myField = field.getAnnotation(MyField.class);
            if (null != myField){
                colName=myField.value();
            }
            sb.append(colName).append("=?,");
        }
        sb.delete(sb.lastIndexOf(","),sb.length());
        sb.append(" where ").append(keyName).append(" = ?");

        QueryRunner qr = new QueryRunner(JDBCUtil.getDataSource());
        try {
            Object[] params=new Object[fields.length+1];
            Object id=null;

            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                String fieldName = field.getName();
                String colName = field.getName();
                MyField myField = field.getAnnotation(MyField.class);
                if (null != myField){
                    colName=myField.value();
                }

                String methodName ="get"+ fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                Method method = aClass.getDeclaredMethod(methodName);
                Object value = method.invoke(obj);
                if (colName.equals(keyName)){
                    id=value;
                }
                params[i]=value;
            }
            params[fields.length]=id;
            row = qr.update(sb.toString(), params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return row;
    }


    //没有写
    public T findById(Object id) {
        return null;
    }


    public int deleteById(Object id){
        int row = 0;
        String sql="delete from "+tableName+" where "+keyName+" =?";
        QueryRunner qr = new QueryRunner(JDBCUtil.getDataSource());
        try {
            row = qr.update(sql, id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }

}
